package com.aliyun.service.impl;

import cn.hutool.json.JSONUtil;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.pojo.AliyunAuthentication;
import com.aliyun.pojo.sms.AliyunSms;
import com.aliyun.pojo.sms.AliyunSmsTemplateParam;
import com.aliyun.teaopenapi.models.Config;
import jakarta.annotation.Resource;

/**
 * 阿里云短信服务
 */
public class AliyunSmsService {

    @Resource
    AliyunCredentialsService aliyunCredentialsService;

    /**
     * @param aliyunSms
     * @return
     * @throws Exception
     */
    public Client createClient(AliyunSms aliyunSms) throws Exception {
        AliyunAuthentication aliyunAuthentication = aliyunCredentialsService.tryGetStsAuthorization(aliyunSms.getStsauthorization());
        Config config = new Config();
        // AliyunSms 服务接入点
        config.setEndpoint(aliyunSms.getEndpoint());
        // 设置Sts临时凭证信息
        config.setAccessKeyId(aliyunAuthentication.getAccessKeyId());
        config.setAccessKeySecret(aliyunAuthentication.getAccessKeySecret());
        config.setSecurityToken(aliyunAuthentication.getSecurityToken());
        return new Client(config);
    }

    /**
     * 发送短信
     * @param phoneNumber 目标手机号
     * @param templateCode  阿里云短信模板码
     * @param templateParam 短信模板参数
     * @return 短信发送结果
     * @throws Exception 抛出异常
     */
    public String sendSms(String phoneNumber , String templateCode , AliyunSmsTemplateParam templateParam) throws Exception {
        // 获取Sms配置信息
        AliyunSms aliyunSms = aliyunCredentialsService.getSms();
        // 创建SmsClient
        Client smsClient = createClient(aliyunSms);
        // 构建请求对象
        SendSmsRequest sendSmsRequest = new SendSmsRequest();
        sendSmsRequest.setPhoneNumbers(phoneNumber);
        sendSmsRequest.setSignName(aliyunSms.getSignName());
        sendSmsRequest.setTemplateCode(templateCode);
        sendSmsRequest.setTemplateParam(JSONUtil.toJsonStr(templateParam));
        // 发送请求
        SendSmsResponse response = smsClient.sendSms(sendSmsRequest);
        return response.getBody().getMessage();
    }
}
